package com.skillscompetition.skillscompetition.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.skillscompetition.skillscompetition.bean.Ranking;
import com.skillscompetition.skillscompetition.bean.SkillScontest;
import com.skillscompetition.skillscompetition.mapper.RankingMapper;
import com.skillscompetition.skillscompetition.mapper.SkillScontestMapper;
import com.skillscompetition.skillscompetition.service.IRankingService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lwg
 * @since 2019-11-09
 */
@Service
public class RankingServiceImpl extends ServiceImpl<RankingMapper, Ranking> implements IRankingService {
    @Autowired
    private SkillScontestMapper skillScontestMapper;
    @Autowired
    private SkillScontestServiceImpl skillScontestService;

    @Override
    @Transactional
    public void sort() {
        QueryWrapper<SkillScontest> wrapper = new QueryWrapper<>();
        List<SkillScontest> skillScontests = skillScontestMapper.getSkillSOperation(wrapper);
        for (SkillScontest skillScontest : skillScontests) {
            float total = (skillScontest.getSubtotal1() * 0.4f) + (skillScontest.getSubtotal2() * 0.3f) + (skillScontest.getSubtotal3() * 0.3f);
            skillScontest.setPracticalOperationSum(total);
            float personageScores = (skillScontest.getTheorys() * 0.4f) + (total * 0.6f);
            skillScontest.setPersonageScores(personageScores);
        }
        Collections.sort(skillScontests);
        List<Ranking> rankingList = new ArrayList<>();
        Ranking ranking = null;
        int sort = 1;
        int sort1 = 1;
        for (SkillScontest skillScontest : skillScontests) {
            ranking = new Ranking();
            ranking.setExamineeId(skillScontest.getExamineeId());
            ranking.setPersonageScores(skillScontest.getPersonageScores());
            ranking.setName(skillScontest.getName());
            ranking.setNumber(skillScontest.getNumber());
            if (skillScontest.getFlag()) {
                ranking.setRanking(sort1);
                sort++;
            } else {
                ranking.setRanking(sort++);
                sort1 = sort;
            }
            rankingList.add(ranking);
        }
        skillScontestService.updateBatchById(skillScontests);
        this.saveOrUpdateBatch(rankingList);
    }

    @Override
    public PageInfo<Ranking> rankingList(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        QueryWrapper<Ranking> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("ranking");
        List<Ranking> rankings = baseMapper.selectList(wrapper);
        PageInfo<Ranking> info = new PageInfo<>(rankings);
        return info;
    }

    @Override
    public void export(HttpServletResponse response) {
        List<Ranking> rankings = this.list();
        //2.加载模板流数据

        //3.根据文件流，加载指定的工作簿
        try {
            Resource resource = new ClassPathResource("excel/个人排名.xlsx");
            FileInputStream fis = new FileInputStream(resource.getFile());
            XSSFWorkbook wb = new XSSFWorkbook(fis);
            //4.读取工作表
            Sheet sheet = wb.getSheetAt(0);
            //5.抽取公共的样式
            Row styleRow = sheet.getRow(2);
            CellStyle[] styles = new CellStyle[styleRow.getLastCellNum()];
            for (int i = 0; i < styleRow.getLastCellNum(); i++) {
                styles[i] = styleRow.getCell(i).getCellStyle();
            }
            //6.构造每行和单元格数据
            AtomicInteger datasAi = new AtomicInteger(2);
            Cell cell = null;
            for (Ranking ranking : rankings) {
                Row dataRow = sheet.createRow(datasAi.getAndIncrement());
                //编号
                cell = dataRow.createCell(0);
                cell.setCellValue(ranking.getNumber());
                cell.setCellStyle(styles[0]);
                //姓名
                cell = dataRow.createCell(1);
                cell.setCellValue(ranking.getName());
                cell.setCellStyle(styles[1]);

                cell = dataRow.createCell(2);
                cell.setCellValue(ranking.getPersonageScores());
                cell.setCellStyle(styles[2]);

                cell = dataRow.createCell(3);
                cell.setCellValue(ranking.getRanking());
                cell.setCellStyle(styles[3]);
            }
            String fileName = URLEncoder.encode("个人排名.xlsx", "UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" + new
                    String(fileName.getBytes("ISO8859-1")));
            response.setHeader("filename", fileName);
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
